package com.efounder.chat.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.Toast;

import com.efounder.chat.R;
import com.efounder.chat.db.WeChatDBManager;
import com.efounder.chat.fragment.SelectGroupContactsFragment;
import com.efounder.chat.fragment.SelectGroupContactsFragment.SelectedCallBack;
import com.efounder.chat.http.GetHttpUtil;
import com.efounder.chat.item.ChatTipsMessageItem;
import com.efounder.chat.model.Group;
import com.efounder.chat.struct.StructFactory;
import com.efounder.chat.utils.ChatActivitySkipUtil;
import com.efounder.chat.utils.GroupAvatarHelper;
import com.efounder.chat.utils.GroupNameUtil;
import com.efounder.chat.utils.GroupOperationHelper;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.frame.utils.Constants;
import com.efounder.message.manager.JFMessageManager;
import com.efounder.message.struct.IMStruct002;
import com.efounder.mobilecomps.contacts.User;
import com.efounder.utils.ResStringUtil;

import org.json.JSONException;

import java.util.ArrayList;
import java.util.List;

import static com.efounder.frame.utils.Constants.CHAT_USER_ID;


/**
 * 创建群组
 *
 * @author yqs
 */
public class CreatChatRoomActivity extends BaseActivity implements
        SelectedCallBack {

    private TextView tv_checked;
    /**
     * 是否为一个新建的群组
     */
    protected boolean isCreatingNewGroup = true;
    private int groupId;
    private Group group;
    private User user = null;
    private ProgressDialog progressDialog;
    private GroupAvatarHelper helper;

    private List<User> selectList = new ArrayList<User>();

    // 选中用户总数,右上角显示
    int total = 0;
    private String groupName = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chatroom);
        helper = new GroupAvatarHelper(this);

        if (getIntent().hasExtra("chatgroup")) {
            isCreatingNewGroup = false;
            group = (Group) getIntent().getSerializableExtra("chatgroup");
            groupId = group.getGroupId();
            groupName = group.getGroupName();
        }
        if (getIntent().hasExtra("selectuser")) {

            isCreatingNewGroup = true;
        }

        TextView tvTitle = (TextView) findViewById(R.id.tv_title);
        tvTitle.setText(getString(R.string.im_select_group_user));
        // 确定按钮
        tv_checked = (TextView) findViewById(R.id.tv_save);
        tv_checked.setVisibility(View.VISIBLE);
        tv_checked.setText(R.string.common_text_confirm);

        SelectGroupContactsFragment selectGroupContactsFragment = (SelectGroupContactsFragment)
                getSupportFragmentManager()
                        .findFragmentById(R.id.fragment_contact);
        selectGroupContactsFragment.setSelectedCallBack(this);
        tv_checked.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                if (selectList != null && selectList.size() != 0) {
                    showLoading(R.string.common_text_please_wait);
                    if (isCreatingNewGroup) {
                        Log.i(TAG, ResStringUtil.getString(R.string.chat_create_new_group));
                        User loginUser = WeChatDBManager.getInstance().getOneUserById(Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID)));
                        groupName = loginUser.getNickName() + "、";
                        StringBuffer bufferName = new StringBuffer();
                        bufferName.append(groupName);
                        for (int i = 0; i < selectList.size(); i++) {
                            bufferName.append(selectList.get(i).getNickName()).append("、");

                        }
                        groupName = bufferName.substring(0,
                                bufferName.length() - 1);
                        if (groupName.length() > 30) {
                            groupName = groupName.substring(0, 30);
                        }

                        try {
                            GetHttpUtil.createGroup(CreatChatRoomActivity.this,
                                    groupName, new GetHttpUtil.ReqCallBack<Group>() {
                                        @Override
                                        public void onReqSuccess(Group group) {
                                            addPeopleToGroup(group);
                                        }

                                        @Override
                                        public void onReqFailed(String errorMsg) {
                                            dismissLoading();
                                            Toast.makeText(CreatChatRoomActivity.this, R.string.chat_create_group_fail,
                                                    Toast.LENGTH_SHORT).show();
                                        }

                                    });

                        } catch (JSONException e) {

                            e.printStackTrace();
                        }


                    } else {// 群组已经存在
                        Log.i(TAG, ResStringUtil.getString(R.string.chat_the_group_already));
                        List<Integer> existIds = new ArrayList<Integer>();
                        String selectIds = "";

                        //找出群组中已经存在的用户 id
                        for (User user : group.getUsers()) {
                            existIds.add(user.getId());
                        }
                        for (User user : selectList) {
//                            if (existIds.contains(user.getId())) {
//                                selectList.remove(user);
//                                continue;
//                            }
                            selectIds = selectIds + user.getId() + ";";

                        }

                        selectIds = selectIds.substring(0, selectIds.length() - 1);
                        Log.i("CreateChatRoomActivity", selectIds);
                        //向服务器群组中添加联系人
                        try {
                            GetHttpUtil.addUserToGroup(CreatChatRoomActivity.this,
                                    group.getGroupId(), selectIds, new GetHttpUtil.ReqCallBack<Boolean>() {
                                        @Override
                                        public void onReqSuccess(Boolean result) {
                                            addGroupUserToDB();
                                        }

                                        @Override
                                        public void onReqFailed(String errorMsg) {
                                            dismissLoading();
                                            Toast.makeText(CreatChatRoomActivity.this, R.string.chat_add_fail,
                                                    Toast.LENGTH_SHORT).show();
                                        }
                                    });

                        } catch (JSONException e) {

                            e.printStackTrace();
                        }
                        group.setUsers(selectList);
//                        if (groupName!= null && groupName.contains("、")){
//                            renameGroup(groupName);
//                   }

                    }
                } else {
                    Toast.makeText(CreatChatRoomActivity.this, R.string.chat_no_contact_select,
                            Toast.LENGTH_SHORT).show();
                }

            }
        });

    }

    //将人员放入群组
    private void addPeopleToGroup(Group group) {
        String ids = EnvironmentVariable.getProperty(CHAT_USER_ID) + ";";
        this.group = group;
        for (User user : selectList) {
            ids = ids + user.getId() + ";";
        }
        ids = ids.substring(0, ids.length() - 1);
        try {
            GetHttpUtil.addUserToGroup(CreatChatRoomActivity.this,
                    group.getGroupId(), ids, new GetHttpUtil.ReqCallBack<Boolean>() {
                        @Override
                        public void onReqSuccess(Boolean result) {
                            dismissLoading();

                            addGroupUserToDB();

                        }

                        @Override
                        public void onReqFailed(String errorMsg) {
                            dismissLoading();
                            Toast.makeText(CreatChatRoomActivity.this, R.string.chat_create_group_fail,
                                    Toast.LENGTH_SHORT).show();

                        }
                    });

        } catch (JSONException e) {

            e.printStackTrace();
        }
    }

    private void addGroupUserToDB() {
        group.setUsers(selectList);
        //得到登录的用户信息
        User appLoginUser = WeChatDBManager.getInstance().getOneUserById(Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID)));
        User groupUser = GroupNameUtil.getGroupUser(group.getGroupId(),
                Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID)));
        int role = User.GROUPCREATOR;
        if (groupUser != null && groupUser.getGroupUserType() != User.GROUPMEMBER) {
            role = groupUser.getGroupUserType();
        }
        // appLoginUser.setGroupUserType(User.GROUPCREATOR);//设置群组用户属性，群组创建者
        appLoginUser.setGroupUserType(role);//设置群组用户属性，群组创建者

        selectList.add(appLoginUser);
        WeChatDBManager.getInstance().insertorUpdateMyGroupUser(group.getGroupId(), selectList);
        //生成新的群组头像
        // GroupAvatarUtil.createNewGroupAvatar(CreatChatRoomActivity.this,group.getCreateId());
        helper.createNewGroupAvatar(group.getGroupId());
        Intent intent = new Intent();
        intent.putExtra("id", group.getGroupId());
        intent.putExtra("chattype", StructFactory.TO_USER_TYPE_GROUP);
        ChatActivitySkipUtil.startChatActivity(CreatChatRoomActivity.this, intent);


        //发送群通知
        String content = GroupOperationHelper.getInviteToGroupMesage(group.getGroupId(), selectList);
        IMStruct002 struct002 = null;
        struct002 = StructFactory.getInstance().
                createCommonNotificationImstruct002(ChatTipsMessageItem.TYPE_NOTIFY, content, null,
                        StructFactory.TO_USER_TYPE_GROUP);
        struct002.setToUserId(group.getGroupId());
        struct002.setFromUserId(Integer.parseInt(EnvironmentVariable
                .getProperty(Constants.CHAT_USER_ID)));
        JFMessageManager.getInstance().sendMessage(struct002);
        finish();
        selectList.clear();
    }


    @Override
    public void getSelectUsers(ArrayList<User> selectList) {
        this.selectList = selectList;
        if (selectList != null) {
            total = selectList.size();
            if (isCreatingNewGroup) {
                // tv_checked.setText("确定(" + total + ")");
                tv_checked.setText(getResources().getString(R.string.im_create_room_enter, total));

            } else {
                // tv_checked.setText("确定(" + total + ")");
                tv_checked.setText(getResources().getString(R.string.im_create_room_enter, total));

            }

        } else {
            tv_checked.setText(R.string.common_text_confirm);
        }

    }


}
